package com.pricetag.googleproductsearch;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import com.google.gson.Gson;
import com.pricetag.helpers.Constants;

public class GoogleShopPriceSearch {
	private String urlstring = "https://www.googleapis.com/shopping/search/v1/public/products?key=AIzaSyDhrjdeGO8HDTsK4TwkiBJG9fVMRfRRQFg";
	private String product;
	private String countryCode;
	private String charset = "UTF-8";
	private String outPutType = "json";

	public ArrayList<GoogleShopPriceSearchResult> getPrice(String keyword, String country) {
		this.countryCode = country;
		// return combination ("", keyword);
		return simpleKeyWord(keyword);
	}

	private ArrayList<GoogleShopPriceSearchResult> search(String keyString) {

		FinalPriceResult finalpriceResult = null;
		ArrayList<GoogleShopPriceSearchResult> resList = new ArrayList<GoogleShopPriceSearchResult>();
		URL url = null;
		InputStream urlInputStream = null;
		Reader reader = null;
		try {
			product = keyString;

			String invokequery = String.format("&country=%s&q=%s&alt=%s", URLEncoder.encode(countryCode, charset),
					URLEncoder.encode(product, charset), URLEncoder.encode(outPutType, charset));

			url = new URL(urlstring + invokequery);
			urlInputStream = url.openStream();
			reader = new InputStreamReader(urlInputStream, charset);

			finalpriceResult = new Gson().fromJson(reader, FinalPriceResult.class);

			if (finalpriceResult.getItems() != null) {
				for (int i = 0; i < finalpriceResult.getItems().size(); i++) {
					System.out.println("--" + finalpriceResult.getItems().get(i).toString());
					for (int j = 0; j < finalpriceResult.getItems().get(i).getProduct().getInventories().size(); j++) {
						GoogleShopPriceSearchResult res = new GoogleShopPriceSearchResult();
						res.setPrice(finalpriceResult.getItems().get(i).getProduct().getInventories().get(j).getPrice());
						res.setAvailability(finalpriceResult.getItems().get(i).getProduct().getInventories().get(j)
								.getAvailability());
						res.setTitle(finalpriceResult.getItems().get(i).getProduct().getTitle());
						res.setLink(finalpriceResult.getItems().get(i).getProduct().getLink());
						res.setImage(finalpriceResult.getItems().get(i).getProduct().getImages().get(j).getLink());
						resList.add(res);
					}
				}
			}

		} catch (Exception ex) {
			System.err.println("Google Product SearchError");
			ex.printStackTrace();
		} finally {
			try {
				if (reader != null) {
					reader.close();
				}
				if (urlInputStream != null) {
					urlInputStream.close();
				}
			} catch (Exception ex) {

			}
		}
		List<GoogleShopPriceSearchResult> subList = resList;
		if (Constants.MAX_GOOGLE_LIST < resList.size()) {
			subList = resList.subList(0, Constants.MAX_GOOGLE_LIST);			
		}		
		Collections.sort(subList);
		resList = new ArrayList<GoogleShopPriceSearchResult>(subList);
		return resList;
	}

	private ArrayList<GoogleShopPriceSearchResult> combination(String prefix, String s) {
		if (s.equals("")) {
			return search(prefix);

		} else {
			String remain;
			if (s.indexOf(' ') != -1) {
				remain = s.substring(s.indexOf(' ') + 1);
			} else
				remain = "";
			ArrayList<GoogleShopPriceSearchResult> toRet = combination(prefix + " " + s.split(" ")[0], remain);
			if (toRet.size() > 0)
				return toRet;
			return combination(prefix, remain);
		}
	}

	private ArrayList<GoogleShopPriceSearchResult> simpleKeyWord(String s) {
		String[] keys = s.split(" ");
		ArrayList<GoogleShopPriceSearchResult> result = new ArrayList<GoogleShopPriceSearchResult>();
		for (int i = keys.length; i >= 1; i--) {
			String temp = "";
			for (int j = 0; j <= i - 1; j++) {
				temp = temp + keys[j];
			}
			result = search(temp);
			if (result.size() > 0)
				break;
		}
		return result;
	}

}
